/**
 * JAVACC DEMO 1.0
 */
package com.apache.uct.common.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.apache.oscache.OsCacheManager;

import com.apache.api.manager.ProxyManager;
import com.apache.api.vo.ParamsVo;
import com.apache.database.constant.SpringContextLoader;
import com.apache.database.constant.SystemTools;
import com.apache.passport.common.PassportHelper;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.ToolsUtil;
import com.apache.uct.common.entity.Role;
import com.apache.uct.service.plugins.ActCacheHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * description:  用户中心服务端过滤器
 */
public class UctServerFilter extends UctSupperFilter {

	private Logger log = LoggerFactory.getLogger(UctServerFilter.class);

	//	private LockManager lockManager;
	private ProxyManager uctProxyManager;

	//	private Map<String, Lock> lockMap = new HashMap<String, Lock>();
	private Map<String, String> unLockMap = new HashMap<String, String>();

	//服务端  白名单路径,iussoft_uct.properties
	private String whiteUrl = "";

	//错误页面地址
	private String errorPage = "";

	/**
	 * 执行过滤
	 *
	 * @exception ServletException , IOException
	 */
	public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain chain)
			throws ServletException, IOException {

		HttpServletRequest request = (HttpServletRequest) srequest;
		HttpServletResponse response = (HttpServletResponse) sresponse;
		response.setCharacterEncoding("UTF-8");
		response.setDateHeader("expires", 0);
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("pragma", "no-cache");
		request.setCharacterEncoding("UTF-8");
		String path = request.getServletPath();
		request.getSession().setAttribute("ctx", request.getContextPath());
		log.debug("访问路径:" + path);
		/**监控白名单处理*/
		if(jkWhite(path)){
			chain.doFilter(request, response);
			return;
		}
		//获取cookie
		String cookieValue = PassportHelper.getInstance().getCurrCookie(request);
		LoginUser loginUser = null;
		if (StrUtil.isNotNull(cookieValue)) {
			loginUser = OsCacheManager.getInstance().getLoginUser(cookieValue);//(LoginUser) request.getSession().getAttribute("loginUser");//从session中获取用户对象
			if (StrUtil.isEmpty(loginUser)) {
				String value = StrUtil.doNull(PassportHelper.getInstance().getCurrCookie(request, "_uc.sso"),request.getHeader("zuulucsso"));
				log.info("uc.sso===" + value);
				//解密
				if (ToolsUtil.isNull(value)) {
					response.sendRedirect(request.getContextPath() + path);
					return;
				}
				if (StrUtil.isNotNull(value)) {
					loginUser = setLoginUser(request, value);
					request.getSession().setAttribute("cookieToken", cookieValue);
					OsCacheManager.getInstance().putLoginUser(cookieValue, loginUser);
				}
			} else {
				String tokenId = String.valueOf(request.getSession().getAttribute("cookieToken"));
				if (!cookieValue.equalsIgnoreCase(tokenId)) {//判断是否变更了新用户
					String value = StrUtil.doNull(PassportHelper.getInstance().getCurrCookie(request, "_uc.sso"),request.getHeader("zuulucsso"));
					loginUser = setLoginUser(request, value);
				}
			}
		} else {
			boolean isMobile = JudgeIsMoblie(request);
			if (isMobile) {
				String tokenId = request.getParameter("tokenId");
				if (ToolsUtil.isNotNull(tokenId)) {
					gotoPage(request, response, chain);
					//chain.doFilter(request, response);
					return;
				}
			} else {
				clearLoginInfo(request, response);
			}
		}
		Iterator<String> it = unLockMap.keySet().iterator();
		while (it.hasNext()) {
			String url = it.next();
			if (path.indexOf(url) > -1) {
				gotoPage(request, response, chain);
				//chain.doFilter(request, response);
				return;
			}
		}
		//白名单处理
		if (unlockPath(path, "uct")) {
			gotoPage(request, response, chain);
			//chain.doFilter(request, response);
			return;
		}
		//如果用户没有登录
		if (null == loginUser) {
			log.error("获取用户对象失败!");
			//跳转到登录页面
			request.getSession().removeAttribute("loginUser");
			request.getSession().removeAttribute("loginUserRoles");
			gotoLogin(request,response,"");
			return;
		}
		String onlyLoginUrl = ToolsUtil.getInstance().getValueByKey("unity_noright_url");
		if (ToolsUtil.isNotNull(onlyLoginUrl)) {
			String[] wus = onlyLoginUrl.split(",");
			for (int i = 0; i < wus.length; i++) {
				String wurl = wus[i];
				if (ToolsUtil.isNotNull(wurl)) {
					if (path.startsWith(wurl)) {
						gotoPage(request, response, chain);
						//chain.doFilter(request, response);
						return;
					}
				}
			}
		}

		if ("1".equals(SystemTools.getInstance().getValue("usage_patterns"))) {
			if (!canAccess(loginUser, path)) {//验证访问权限
				gotoLogin(request,response,"对不起,您没有访问权限!!");
				log.error("没有操作权限");
				return;
			}
		}
		//chain.doFilter(request, response);
		gotoPage(request, response, chain);
	}

	private LoginUser setLoginUser(HttpServletRequest request, String userEname) {
		ParamsVo vo = new ParamsVo();
		vo.setParams("userEname", userEname);
		vo.setKey("loginUser");
		LoginUser loginUser = (LoginUser) getProxyManager().doInvoke(vo);
		if (!StrUtil.isEmpty(loginUser)) {
			request.getSession().setAttribute("loginUser", loginUser);
			request.getSession().setAttribute("sysUser", loginUser.getSysFlag());
			Object objRoles = OsCacheManager.getInstance().getCustomerUser(loginUser.getUser().getUserId());
			if (StrUtil.isEmpty(objRoles)) {
				List<Role> roles = ActCacheHelper.getInstance().getRolesForUserEname(loginUser.getUserEname());//获取用户角色列表
				if (!StrUtil.isEmpty(roles)) {
					request.getSession().setAttribute("loginUserRoles", roles);
					OsCacheManager.getInstance().putCustomerUser(loginUser.getUser().getUserId(),roles);
				}
			}
		}
		return loginUser;
	}

	private boolean canAccess(LoginUser loginUser, String path) {
		boolean mark = false;
		if (loginUser.getUserEname()
				.equals(StrUtil.doNull(SystemTools.getInstance().getValue("uct_supper_user"), "admin"))) {
			return true;
		}
		mark = this.canAccess(loginUser, path);
		return mark;
	}

	private ProxyManager getProxyManager() {
		if (null == uctProxyManager) {
			uctProxyManager = (ProxyManager) SpringContextLoader.getBean("uctProxyManager");
		}
		return uctProxyManager;
	}

	/**
	 * TODO 简单描述该方法的实现功能（可选）.
	 */
	public void destroy() {

	}

	public void init(FilterConfig arg0) throws ServletException {
		this.initLincense();
		//初始化uct服务端 白名单配置
		unLockMap.put("/common/image.jsp", "");
		unLockMap.put("/uct/service/", "");
		unLockMap.put("/login.jsp", "");
		unLockMap.put("/mobile/service", "");
		unLockMap.put("/error.action", "");
		if (StrUtil.isNotNull(whiteUrl)) {
			String[] wus = whiteUrl.split(",");
			for (int i = 0; i < wus.length; i++) {
				String wurl = wus[i];
				if (StrUtil.isNotNull(wurl)) {
					unLockMap.put(wurl, "");
				}
			}
		}
		String isFilter = StrUtil.doNull(SystemTools.getInstance().getValue("is_open_security_filter"), "false");
		isOpenSecurityFilter = Boolean.parseBoolean(isFilter);
		//错误页面地址
		errorPage = StrUtil.doNull(arg0.getInitParameter("errorPage"), "/error.action");
	}
}
